/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frm.billingAndPaymentProcessing.managedbean;

import commonInfrastructure.accountManagement.session.EmployeeSessionBean;
import crm.salesOrderProcessing.entity.DeliveryOrderEntity;
import crm.salesOrderProcessing.entity.LineItemEntity;
import frm.billingAndPaymentProcessing.entity.InvoiceEntity;
import frm.billingAndPaymentProcessing.entity.ReceiptEntity;
import frm.billingAndPaymentProcessing.session.InvoiceSessionBean;
import frm.billingAndPaymentProcessing.session.ReceiptSessionBean;
import frm.creditControl.entity.CreditAccountEntity;
import frm.creditControl.session.CreditControlSessionBean;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import org.primefaces.event.ToggleEvent;
import scm.supplyChainManagement.session.DeliveryOrderSessionBean;

/**
 *
 * @author xhx
 */
@ManagedBean
@ViewScoped
public class ManageInvoiceManagedBean {

    private InvoiceEntity invoice;
    private String displayMessage;
    private boolean isPaymentneed = false;
    private double paymentAmount = 0;
    private DeliveryOrderEntity deliveryOrder;
    private boolean receiptIssued = false;
    private List<LineItemEntity> dLineItem;
    private boolean idDued;
    private String employeeName;
    @EJB
    InvoiceSessionBean invoiceSessionBean;
    @EJB
    DeliveryOrderSessionBean deliveryOrderSessionBean;
    @EJB
    ReceiptSessionBean receiptSessionBean;
    
    @EJB
    CreditControlSessionBean creditControlSessionBean;
    
    @EJB
    EmployeeSessionBean employeeSessionBean;
    /** Creates a new instance of DisplayInvoiceManagedBean */
    public ManageInvoiceManagedBean() {
    }

    public void initView(PhaseEvent event) {

        if (invoice == null) {
            setInvoice((InvoiceEntity) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("invoice"));

        }
//         setDisplayMessage(FacesContext.getCurrentInstance().getExternalContext().getFlash().get("message").toString());
        if (invoice.getPayment_balance() < 0) {
            isPaymentneed = true;
        }
        if (invoice.getReceipt() != null) {
            receiptIssued = true;
        }
        idDued = checkDate();
        deliveryOrder = invoice.getDeliveryOrder();
        setdLineItem(deliveryOrder.getLineItems());
        setEmployeeName(employeeSessionBean.getEmployeeById(invoice.getCreatedBy()).getName());
    }

//    public void updatePayment(ActionEvent event) throws IOException {
//        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoice", getInvoice());
//        FacesContext.getCurrentInstance().getExternalContext().redirect("updatePayment.xhtml");
//        //direct to the updatePage     
//    }
    private Boolean checkDate(){
        boolean check = false;
        Date todayDate = Calendar.getInstance().getTime(); 
        if(invoice.getDueDate().before(todayDate))
            check = true;
        return check;
    }
    public void sendDunningEmail() throws IOException{
       FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoice", getInvoice());
       FacesContext.getCurrentInstance().getExternalContext().redirect("commenceDunningEmail.xhtml");
    }
    public void abolishInvoice() {
        if (invoice.getReceipt() != null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Receipt Has Been Already Issued, you are not allowed to abolish this Invoice", ""));
            return;
        } else {
            invoice.setAbolished(true);
//        DeliveryOrderEntity deliveryOrder = invoice.getDeliveryOrder();
            if (deliveryOrder != null) {
                deliveryOrder.setInvoice(null);
                deliveryOrderSessionBean.saveChanges(deliveryOrder);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Invoice is Successfully aboloshed", ""));
            }

            invoiceSessionBean.saveChanges(invoice);

            //******************************display the result
        }
    }
//
//    public void removeInvoice() {
//        DeliveryOrderEntity deliveryOrder = invoice.getDeliveryOrder();
//        System.out.println("!!!!*******************");
//        if (deliveryOrder != null) {
//            deliveryOrder.setInvoice(null);
//            deliveryOrderSessionBean.saveChanges(deliveryOrder);
//        }
//        invoice.setDeliveryOrder(null);
//        
//        System.out.println("!!!!*******************2");
////        invoiceSessionBean.saveChanges(invoice);
//        System.out.println("!!!!*******************3" + invoice.getId());
//        invoiceSessionBean.removeInvoice(invoice);
//        
//    }

    public void issueReceipt() throws IOException {
        ReceiptEntity receipt = new ReceiptEntity();
        if (invoice.getReceipt() == null) {
            if (invoice.getPayment_balance() >= 0l) {
                receipt.setInvoice(invoice);
                receipt.setIssuingDate(Calendar.getInstance().getTime());
                invoice.setReceipt(receipt);
                invoiceSessionBean.saveChanges(invoice);
                receiptIssued = true;
//            receiptSessionBean.createReceipt(receipt);
                //send receipt to customer
                FacesContext.getCurrentInstance().getExternalContext().getFlash().put("receipt", receipt);
                FacesContext.getCurrentInstance().getExternalContext().redirect("receiptSheet.xhtml");
            }
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Customer's Payment Balance is not Cleaned, Pls Check", ""));
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The Receipt Has already be issued", ""));
    }

    public List<DeliveryOrderEntity> formDeliveryOrderList() {
        List<DeliveryOrderEntity> dOrderList = new ArrayList<DeliveryOrderEntity>();
        dOrderList.add(deliveryOrder);
        return dOrderList;
    }


    public void updatePayment() {
       if((paymentAmount + invoice.getPayment_balance())>0l){
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Payment Made exceeds amount payable, Please revise the number", ""));   
        return;
        }
        invoice.addAmountPaid(paymentAmount);
        invoice.setPayment_balance();

        if(invoice.getInvoiceType().equals("Credit Sale Invoice")){
        CreditAccountEntity creditAccount = deliveryOrder.getParentSalesOrder().getCustomer().getCreditAccount();
        creditAccount.setCurrentBalance(invoice.getPayment_balance());
        creditControlSessionBean.saveChanges(creditAccount);
        }
        if (invoice.getPayment_balance() == 0l) {
            invoice.setIsPaid(true);
        }
       
        invoice.setPaymentDate(Calendar.getInstance().getTime());

        invoiceSessionBean.saveChanges(invoice);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Customer's Payment is Sucessfully updated", ""));
    }

    public void viewAll() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("viewAllInvoices.xhtml");
    }

    public void handleToggle(ToggleEvent event) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Fieldset Toggled", "Visibility:" + event.getVisibility());

        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public String getDisplayMessage() {
        return displayMessage;
    }

    public void setDisplayMessage(String displayMessage) {
        this.displayMessage = displayMessage;
    }

    public InvoiceEntity getInvoice() {
        return invoice;
    }

    public void setInvoice(InvoiceEntity invoice) {
        this.invoice = invoice;
    }

    public boolean isIsPaymentneed() {
        return isPaymentneed;
    }

    public void setIsPaymentneed(boolean isPaymentneed) {
        this.isPaymentneed = isPaymentneed;
    }

    public double getPaymentAmount() {
        return paymentAmount;
    }

    public void setPaymentAmount(double paymentAmount) {
        this.paymentAmount = paymentAmount;
    }

    public DeliveryOrderEntity getDeliveryOrder() {
        return deliveryOrder;
    }

    public void setDeliveryOrder(DeliveryOrderEntity deliveryOrder) {
        this.deliveryOrder = deliveryOrder;
    }

    public boolean isReceiptIssued() {
        return receiptIssued;
    }

    public void setReceiptIssued(boolean receiptIssued) {
        this.receiptIssued = receiptIssued;
    }

    public List<LineItemEntity> getdLineItem() {
        return dLineItem;
    }

    public void setdLineItem(List<LineItemEntity> dLineItem) {
        this.dLineItem = dLineItem;
    }

    public boolean isIdDued() {
        return idDued;
    }

    public void setIdDued(boolean idDued) {
        this.idDued = idDued;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }


    
}
